import React from 'react';
import { observer,inject } from 'mobx-react';
import { withRouter, Switch, Route,  } from 'react-router-dom';
import { Icon, Tools, DateSwitch, Carousel ,Bubble } from 'weaver-mobile';
import { Browser, RouteLayout } from 'weaver-mobile-page';
import moment from 'moment';
import * as Api from '../../api/roomPlan';
import RoomUsedDetail from '../../components/roomPlan/roomUsedDetail';
import { isIOS } from '../../util/util';
const getLabel = Tools.getLabel;
@inject('roomPlanStore')
@inject('calendarStore')
@inject('viewMeetingStore')
@withRouter
@observer
export default class roomDisplay extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      currentdate: '', // 当前时间
      roomMeetTabs: [],  // roomTabs中的会议和roomid中会议id一一对应
      roomMeetID: [],
      useMap: [], // key为roomid,value为使用信息
      dspUnit: 0, // 一个小时分成dspUnit个单元
      duration: 0, // 最小间隔时间
      mask: false,
      currentRoomid: '',
      rooms: [],
      selectRoomIds: [],
      imgdata: ['AiyWuByWklrrUDlFignR', 'TekJlZRVCjLFexlOCuWn',],
      filterType: true,
      scrollType: '',
      loading: false,
    }
  }

  componentDidMount() {
    const {getRoomReportBaseData,initRoomBrowser} = this.props.roomPlanStore;
    const { selectdate, roomUsedSelectDate } = this.props.calendarStore;
    let params = {};
    if(window.iNoBounce && window.iNoBounce.isEnabled()) {
      isIOS() && window.iNoBounce.disable(); // 解决ios滑动问题
    }
    if(selectdate && selectdate !== ''){
      this.setState({currentdate:selectdate})
      params = {currentdate: selectdate}
    }else{
      this.setState({currentdate:moment(new Date()).format("YYYY-MM-DD")})
      params = {currentdate:moment(new Date()).format("YYYY-MM-DD")}
    }
    if(roomUsedSelectDate !== '') {
      params.currentdate = roomUsedSelectDate;
      this.setState({currentdate: roomUsedSelectDate});
    }
    getRoomReportBaseData();// 初始化基本数据
    this.getRoomUsedInfo({...params,roomid: this.state.selectRoomIds},this.tableScroll); // 查询会议室
    // this.tableScroll();
    initRoomBrowser(this.props.location.pathname)
    if(this.props.location.pathname=='/calendar/allMeeting/report/roomPlan'){
      window.em&&window.em.checkJsApi('changeTitle') && window.em.changeTitle({title:getLabel(15881, '会议室使用情况')})
    }
  }

  componentWillUnmount() {
    // if(window.iNoBounce && !window.iNoBounce.isEnabled()) {
    //   window.iNoBounce.enable(); // 组件卸载后，还原解决ios滑动问题时的设置
    // }
  }

  componentWillReceiveProps (nextProps) {
    const prePath = this.props.location.pathname;
    const curPath = nextProps.location.pathname;
    if (curPath && curPath !== prePath) {
      if(curPath.indexOf('roomUsedDetail') < 0){
        window.em&&window.em.checkJsApi('changeTitle') && window.em.changeTitle({title:getLabel(15881, '会议室使用情况')})
      }
    }
  }
  getRoomUsedInfo = (params, callback) => {
    Api.getRoomReportData(params).then((res) => {
      let arrRoom = [];
      let arrID = [];
      let useMap = {};
      let rooms = [];
      let dspUnit = res&&res.dspUnit ? res.dspUnit : 0;
      
      // 会议室
      res && res.rooms && res.rooms.map(key => {
        let objRoom = {};
        let objID = {};
        objRoom.title = key.name;
        objRoom.key = key.id;
        objID.id = key.id;
        arrRoom.push(objRoom);
        arrID.push(objID);
        rooms[key.id] = key;
        return 0;
      });
      // 会议室中会议信息
      res.datas && res.datas.forEach((obj) => {
        if(!obj.roomid) return;
        useMap[obj.roomid] = obj.info;
      });
      this.setState({
        useMap: useMap,
        roomMeetTabs: arrRoom,  // roomTabs中的会议和roomid中会议id一一对应
        roomMeetID: arrID,
        dspUnit: dspUnit,
        duration: 60/dspUnit,
        rooms: rooms,
        loading: res.api_status
      },callback);
    })
  }
  
  tableScroll = () => { // 解决事件相互冲突
    let Table = this.refs.roomplanTable;
    const fnStart = (e) => {
      if(e.target.className === 'dsp-unit') {
        this.setState({scrollType: 'table'});
      }else if(e.target.className === 'item') {
        if(e.target.parentNode.parentNode.className === 'roomplan-table-top-content') {
          this.setState({scrollType: 'top'});
        }else if(e.target.parentNode.parentNode.className === 'roomplan-table-box-content') {
          this.setState({scrollType: 'table'});
        }
      }else if(e.target.className === 'table-box') {
        if(e.target.parentNode.className === 'roomplan-table-box-content') {
          this.setState({scrollType: 'table'});
        }
        if(e.target.parentNode.className === 'roomplan-table-top-content') {
          this.setState({scrollType: 'top'});
        }
      }else if(e.target.className === 'head-item') {
        this.setState({scrollType: 'head'});
      }
    }
    Table.addEventListener('touchstart',fnStart,false);
  }

  onChangeDate = (date) => {
    const { setState } = this.props.calendarStore;
    setState({ roomUsedSelectDate: date});
    let param = {currentdate: date, roomid: this.state.selectRoomIds};
    sessionStorage.setItem('meetingRoomPlanDate',date)
    this.getRoomUsedInfo(param);
  }

  getTabar = () => {
    let fields = [];
    const { color, startHour, endHour, browser1} = this.props.roomPlanStore; 
    fields.push(
      <div className="legend" key='legend' ref='legend'>
        <div style={{paddingTop: 5}}>
        {this.state.currentdate !== '' ?<DateSwitch date={new Date(this.state.currentdate)} defaultValue onChange={date => this.onChangeDate(date)} />:''}
        </div>
        <div className="wea-meetingRoom-cirlceSpan" title={getLabel(127867,"冲突")}>
          <div className="square" style={{backgroundColor: color.conflictedColor,height:10,width:10,borderRadius:'50%'}}/>
          <div className='squareName'>{getLabel(127867,"冲突")}</div>
        </div>
        <div className="wea-meetingRoom-cirlceSpan" title={getLabel(2242,"待审批")}>
          <div className="square" style={{backgroundColor: color.agreementColor,height:10,width:10,borderRadius:'50%'}}/>
          <div className='squareName'>{getLabel(2242,"待审批")}</div>
        </div>
        <div className="wea-meetingRoom-cirlceSpan" title={getLabel(383468,"占用")}>
          <div className="square" style={{backgroundColor: color.usedColor,height:10,width:10,borderRadius:'50%'}}/>
          <div className='squareName'>{getLabel(383468,"占用")}</div>
        </div>
      </div>
    )
    return fields;
  }

  getTimeItem = () => {
    const {startHour,endHour} = this.props.roomPlanStore;
    let grounp = [];
    let fields = [];
    for(let i=startHour; i<=endHour; i++) {
      fields.push( // 时间段格
        <div className='item' key={i}>{i}</div>
      )
    }
    return fields;
  }


  setBG = (time, id) => {
    const {useMap} = this.state;
    let bgColor = '';
    if(useMap && useMap[id]) {
      useMap[id].map((res, index) => {
        let t = parseInt(res.time.replace(':',''),10);
        if(time === t) {
          bgColor = res.bgcolor;
        }
      })
    }
    return bgColor;
  }

  getMeetingIDs = (time, id) => {
    const {useMap} = this.state;
    // console.log('time',time)
    // console.log('useMap',useMap[id])
    let meetingIds = [];
    if(useMap && useMap[id]) {
      useMap[id].map((res, index) => {
        let t = parseInt(res.time.replace(':',''),10);
        if(time === t) {
          res.meetings && res.meetings.map(res => {
            meetingIds.push(res.id);
          })
        }
      })
    }
    return meetingIds;
  }

  clickRoomId = (id) => {
    this.setState({mask: true,currentRoomid: id});
  }

  setNum = (num) => {
    if(num > 9){
      return num;
    }else{
      return '0'+num;
    }
  }

  previewMeetingInfo = (params) => {
    //会议室使用情况使用的场景
    //会议信息中
    const { duration } = this.state;
    const nowPathName = this.props.location.pathname
    let meetingIDArr = [];
    meetingIDArr = params.getAttribute('meetingids');
    const {setState,onlyFlowCreate, hideCreateEntry, workflowBaseIds,requestFieldIds,addRequestUrlParams} = this.props.viewMeetingStore;
    let roomid = '';
    if(params.className === 'dsp-unit') {
      roomid = params.parentNode.parentNode.getAttribute('roomid');
    }else if(params.className === 'item') {
      roomid = params.parentNode.getAttribute('roomid');
    }
    
    if(meetingIDArr === '') {
      const createMeeting = ()=>{
        const{ from } = this.props;
        let time = 0;
        let startTime = '';
        let endTime = '';
        // sessionStorage.setItem('address',roomid)
        time = parseInt(params.getAttribute('starttime'),10);
        startTime = this.setNum(Math.floor(time/100)) + ':' + this.setNum(time%100);
        endTime = this.setNum(Math.floor((time-1+parseInt(duration,10))/100)) + ':' + this.setNum((time-1+parseInt(duration,10))%100);
        if(from === 'calendar'){
          let workflowBaseIdsArr = [];
          if(workflowBaseIds !== ''){
            workflowBaseIdsArr = workflowBaseIds.split(',')
          }
          if(hideCreateEntry == 1){
            return Bubble.error(getLabel(510049, '请通过流程新建会议！'), 3);
          }else if(onlyFlowCreate == 1 && hideCreateEntry ==0 &&  workflowBaseIdsArr.length === 0){
            return Bubble.error(getLabel(510148, '系统查找不到新建会议流程！'), 3);
          }else{
            sessionStorage.setItem('type','create');
            let urlParamsTemp = [];
            const curmoment = sessionStorage.meetingRoomPlanDate || moment(new Date()).format("YYYY-MM-DD")
            requestFieldIds&&Object.keys(requestFieldIds).map((item)=>{
              if(item === 'begindate'){
                requestFieldIds.begindate&&requestFieldIds.begindate.map(item1=>{
                  urlParamsTemp.push(`&${item1}=${curmoment}`)
                })
              }
              if(item === 'begintime'){
                requestFieldIds.begintime&&requestFieldIds.begintime.map(item1=>{
                  startTime&&urlParamsTemp.push(`&${item1}=${startTime}`)
                })
              }
              if(item === 'enddate'){
                requestFieldIds.enddate&&requestFieldIds.enddate.map(item1=>{
                  urlParamsTemp.push(`&${item1}=${curmoment}`)
                })
              }
              if(item === 'endtime'){
                requestFieldIds.endtime&&requestFieldIds.endtime.map(item1=>{
                  endTime&&urlParamsTemp.push(`&${item1}=${endTime}`)
                })
              }
              if(item === 'address'){
                requestFieldIds.address&&requestFieldIds.address.map(item1=>{
                  roomid&&urlParamsTemp.push(`&${item1}=${roomid}`)
                })
              }
              if(item === 'beginDateTime'){
                requestFieldIds.beginDateTime&&requestFieldIds.beginDateTime.map(item1=>{
                  curmoment&&startTime&&urlParamsTemp.push(`&${item1}=${curmoment} ${startTime}`)
                })
              }
              if(item === 'endDateTime'){
                requestFieldIds.endDateTime&&requestFieldIds.endDateTime.map(item1=>{
                  curmoment&&endTime&&urlParamsTemp.push(`&${item1}=${curmoment} ${endTime}`)
                })
              }
            })
            let url = onlyFlowCreate == 1 && hideCreateEntry ==0 && workflowBaseIdsArr.length === 1?`/spa/workflow/static4mobileform/index.html#/req?iscreate=1&src=meeting&workflowid=${workflowBaseIds}${urlParamsTemp.join('')}`
            :onlyFlowCreate == 1 && hideCreateEntry ==0 && workflowBaseIdsArr.length > 1?`/spa/workflow/static4mobile/index.html#/add?isNeedTab=0&src=meeting&wfRange=${workflowBaseIds}${urlParamsTemp.join('')}`:''
            if(url !== ''){
              window.location.href = url
            }else{
              setState({addRequestUrlParams: urlParamsTemp.join('')}, ()=>this.props.history.push({pathname:`/calendar/detail`,query:{
                meetingid:'',
                type:'create',
                roomPlanSelectDate: sessionStorage.meetingRoomPlanDate || moment(new Date()).format("YYYY-MM-DD"),
                meetingRoomBeginTime:startTime,
                meetingRoomEndTime:endTime,
                address: roomid
                }})
              )
            }
          }
        }
      }
      setState({is_create: true}, ()=>createMeeting());
    }else{
      this.props.history.push(`${nowPathName}/roomUsedDetail`)
      const { getRoomMeetingList} = this.props.roomPlanStore;
      getRoomMeetingList({meetingIds: meetingIDArr,roomid:roomid,selectDate:sessionStorage.meetingRoomPlanDate || moment(new Date()).format("YYYY-MM-DD")})
    }
  }

  getRoomItem = () => {
    const {roomMeetTabs,useMap,dspUnit,duration,mask} = this.state;
    const {startHour,endHour} = this.props.roomPlanStore;
    let startTime = 0, endTime = 0;
    let counting = dspUnit;
    let bgcolor = '';
    let meetingIDArr = [];
    let fields = [];
    let field = [];
    let table = [];
    let HH = this.refs.roomplanTableBox ? this.refs.roomplanTableBox.offsetHeight : '';
    const dspunit = (roomid,time) => { // 渲染单元格颜色
      let T = time*100;
      const {useMap} = this.state;
      let dspArr = [];
      if(useMap && useMap[roomid]) {
        let len = useMap[roomid].length;
        startTime = parseInt(useMap[roomid][0].time.replace(':',''),10);
        endTime = parseInt(useMap[roomid][len-1].time.replace(':',''),10);
      }

      let tt = T;
      for(let i=0; i<dspUnit; i++){ // 单元格颜色
        if(useMap && useMap[roomid] && tt >= startTime && tt <= endTime){
          bgcolor = this.setBG(tt, roomid);
          meetingIDArr = this.getMeetingIDs(tt, roomid);
        }else{
          bgcolor = '';
          meetingIDArr = [];
        }
        tt = tt + duration;
        dspArr.push(
          <div className='dsp-unit' key={i} starttime={tt-duration} meetingids={meetingIDArr} style={{width: 30/dspUnit,backgroundColor: bgcolor}} onClick={(e) => {this.previewMeetingInfo(e.target)}}></div>
        );
      }
            
      return dspArr;
    }

    roomMeetTabs && roomMeetTabs.map((res, index) => {
      let group = [];
      const {dspUnit} = this.state;
      field.push(
        <div className='head-item' key={index} onClick={() => {this.clickRoomId(res.key)}}>{res.title}</div>
      );
      for(let i=startHour; i<=endHour; i++) {
        let bgcolor = dspUnit===1 ? this.setBG(i*100, res.key) : '';
        let meetingIDArr = dspUnit===1 ? this.getMeetingIDs(i*100, res.key) : [];
        group.push( // 时间段格--单元小格
          <div className='item' key={i} starttime={i*100} style={{backgroundColor: bgcolor}} meetingids={meetingIDArr} 
                onClick={(e) => {dspUnit===1 ? this.previewMeetingInfo(e.target) : ''}}
                >
            {dspUnit>1 && dspunit(res.key,i)} 
          </div>
        )
      }
      table.push(
        <div className='table-box' key={index} roomid={res.key}>{group}</div>
      )
    });
    fields.push(
      <div className='roomplan-table-box-head' ref='roomplanTableBoxHead' key='roomplanTableBoxHead' onScroll={this.onHeadScroll} style={{height: HH}}>{field}</div>,
      <div className='roomplan-table-box-content' key='table' ref='roomplanTableBoxContent' 
        style={{height: HH,overflow: mask?'hidden':'auto'}} onScroll={this.onscroll} >{table}</div>,
    )
    return fields;
  }

  onTopScroll = (e) => {
    let table = this.refs.roomplanTableBoxContent;
    let topTime = this.refs.topTime;
    
    if(this.state.scrollType === 'top'){
      table.scrollLeft = topTime.scrollLeft;
    }
  }

  onHeadScroll = (e) => {
    let table = this.refs.roomplanTableBoxContent;
    let roomplanTableBoxHead = this.refs.roomplanTableBoxHead;

    if(this.state.scrollType === 'head') {
      table.scrollTop = roomplanTableBoxHead.scrollTop;
    }
  }

  onscroll = (e) => {
    let roomplanTableBoxHead = this.refs.roomplanTableBoxHead;
    let topTime = this.refs.topTime;
    let table = this.refs.roomplanTableBoxContent;
    if(this.state.scrollType === 'table') {
      topTime.scrollLeft = table.scrollLeft
      roomplanTableBoxHead.scrollTop = table.scrollTop;
    }
  }


  changeRoomMeetTab = (params) => {
    if(params === ''){
      this.setState({selectRoomIds: params,filterType: true});
    }else{
      this.setState({selectRoomIds: params,filterType: false});
    }
    this.getRoomUsedInfo({currentdate: this.state.currentdate,roomid: params});
  }

  getTable = () => {
    const {browser1} = this.props.roomPlanStore; 
    const {filterType} = this.state;
    let fields = [];
    fields.push(
      <div className='roomplan-table' ref='roomplanTable' key='roomplanTable'>
        <div className='roomplan-table-top' ref='roomplanTableTop' style={{}}>
          <div className='roomplan-table-top-head'>
            <Browser
              label='browser'
              store={browser1}
              hasAdvanceSerach
              isSingle={false}
              type={184}
              onChange={(arg) => {
                this.changeRoomMeetTab(arg)
              }}
            >
              {filterType ? <Icon type='filter-o' size='sm'/> :
                <Icon type='filter-o-hot' color={window.getThemeVars()['less']['brand-primary']} size='sm'/>}
            </Browser>
          </div>
          <div className='roomplan-table-top-content' ref='topTime' onScroll={this.onTopScroll} >
            <div className='table-box'>{this.getTimeItem()}</div>
          </div>
        </div>
        <div className='roomplan-table-box' ref='roomplanTableBox'>
          {this.getRoomItem()}
        </div>
      </div>
    );

    return fields;
  }

  clickMask = (e) => {
    if(e.target.className === 'mask'){
      this.setState({mask: false});
    }
  }

  getMask = () => {
    let fields = [];
    const {currentRoomid,rooms,useMap} = this.state;
    let roomObj = rooms[currentRoomid] ? rooms[currentRoomid] : [];
    let img = roomObj.img;
    fields.push(
      <div className='mask' onClick={this.clickMask} key='mask'>
        <div className="mask-content">
          <div className='title'>
            <div className='titile-text'>{roomObj.name}</div>
          </div>
          <div className='img'>
            {/* 'https://www.e-cology.com.cn/messager/usericon/108d0c185df148caa920a39a8f8979d0.jpg' */}
            {img instanceof Array && img.length == 0 ? <div><img style={{width:'100%',height:'100%'}} src='/cloudstore/resource/pc/com/images/meeting_default.png' /></div> :
              <Carousel
                autoplay={false}
                infinite
                vertical={false}
              >
                {img && (img instanceof Array) && img.map(res => {
                  return <a style={{display: 'inline-block',width: '100%',height: 180}}>
                    <img
                      src={res} // require('./1.jpg')
                      alt=""
                      style={{width: '100%',height: 180}}
                      onLoad={() => {
                        // fire window resize event to change height
                        window.dispatchEvent(new Event('resize'));
                      }}
                    />
                  </a>
                })}
              </Carousel>
            }
          </div>
          <div className='message'>
            <div className=''>
              <span>{roomObj.title[1]}</span>
            </div>
            <div className=''>
              <span>{roomObj.title[2]}</span>
            </div>
            <div className=''>
              <span>{roomObj.title[3]}</span>
            </div>
          </div>
        </div>
        <div className='mask-close'>
          <Icon type='cross-circle-o' color='#424242' onClick={() => {this.setState({mask: false})}}/>
        </div>
      </div>
    )
    return fields;
  }

  getLoading = () => {
    return (
      <div className='loaidng-icon' key='loading'>
          <Icon type='loading' size='lg'/>
      </div>
    );
  }

  render() {
    const {mask,loading} = this.state;
    return (
      <div className='roomplan-display2' style={{height: '100%'}}>
        {this.getTabar()}
        {loading ? this.getTable() : this.getLoading()}
        {mask && this.getMask()}
        <Switch>
          <Route
            key="roomUsedDetail"
            path="/calendar/*/roomPlan/roomUsedDetail"
            render={()=>(
              <RouteLayout>
              <div key="roomUsedDetailDiv" className="wm-route-layout wm-demo-route-layout-page">
                <RoomUsedDetail />
              </div>
              </RouteLayout>
            )}
          />
          
          <Route
            key="roomUsedDetailForView"
            path="/roomPlan/roomUsedDetail"
            render={()=>(
              <RouteLayout>
              <div key="roomUsedDetailForViewDiv" className="wm-route-layout wm-demo-route-layout-page">
                <RoomUsedDetail />
              </div>
              </RouteLayout>
            )}
          />
          
        </Switch>
      </div>
    )
  }
}